[C++]如何读取一个txt文件并且将里面的数字用相应大小的数组载入?

来源:百度知道 编辑:UC知道 时间:2024/05/27 01:53:21
读取一个txt文件,形式如下:
1111111111
0110001111
0010101101
1010101000
这个数字矩阵的行数和列数都不固定,不过里面都是数字。如何用相应大小的数组载入?我定义一个a[m][n]数组可是m,n不能为变量啊!还有一个问题:我是将每行数字读为一个string可是不知道如何将string里的每一个数字一一取出来赋给数组?我这边学的很混乱,大家帮帮忙,看还有什么更好的思路实现目的!或者用什么getline()之类的读入都行,只要能实现目的就可以!事成之后再加50分!

思路:

String str;

假设你对str读入了所有字符并获得一个字符串字符的长度n
那么就可以定义一个行列目录为(根号n)+1的数组
row=(根号n)+1
col=(根号n)+1
可能定义一个string指针 *pstr

int **pint=new int*[row] //row是二维数组的行,*pint是指向一个指针数组的指针

for(int i=0;i<row;i++)

{ *pint=new int[col]};//col是二维数组的列,pint是指向一个int数组的指针
int count=0;
for( i=0;i<row;row++)
for( k=0;i<col;col++)
{
*(*(pint+k)+i)=*(pstr+count)-48;
count++;
}

我知道,请加我HI,明天答复你,因为要熄灯了~~

#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
int fd;
struct stat buf;
if((fd = open("test.txt", O_RDONLY|_O_BINARY)) == -1) return 0;

if(fstat(fd, &buf)) return 0;

char *outbuf = (char*)calloc(1, buf.st_size+1);
if(!outbuf) return 0;
read(fd, outbuf, buf.st_size);

int